/**
 * Filename: NewsInviteFragment.java
 *
 * @author Firefly
 * @contact postfirefly@163.com
 * @time 2016/3/4 12:08
 */
package com.github.postsanf.yinian.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.OvershootInterpolator;
import android.widget.Toast;

import com.github.postsanf.yinian.BaseFragment;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.adapter.NewsInviteAdapter;
import com.github.postsanf.yinian.bean.YNAlbum;
import com.github.postsanf.yinian.bean.YNNewsInvite;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.entity.YNAlbumResponse;
import com.github.postsanf.yinian.entity.YNCommonResponse;
import com.github.postsanf.yinian.service.NewsService;
import com.github.postsanf.yinian.utils.ReqUtils;
import com.github.postsanf.yinian.utils.WrapContentLinearLayoutManager;
import com.github.postsanf.yinian.ynlist.EndlessRecyclerOnScrollListener;
import com.github.postsanf.yinian.ynlist.LoadingFooter;
import com.github.postsanf.yinian.ynlist.RecyclerViewStateUtils;
import com.github.postsanf.yinian.ynlist.YNRecyclerViewAdapter;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;
import com.umeng.analytics.MobclickAgent;

import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;

import jp.wasabeef.recyclerview.animators.FadeInAnimator;

/**
 * 消息-邀请
 */
public class NewsInviteFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener {
    private View view;
    private NewsInviteAdapter mAdapter;
    private RecyclerView rv_news_list;
    private WrapContentLinearLayoutManager mLinearLayoutManager;
    private LinkedList<YNNewsInvite> mInviteDatas = new LinkedList<>();
    private SwipeRefreshLayout mRefreshlayout;
    private Handler handler;
    private boolean isBottom;
    private YNRecyclerViewAdapter mYNRecyclerViewAdapter;

    // 注册广播接收过滤
    private void registerBroadcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(ACTIONs.actionInviteUpdate);
        myIntentFilter.addAction(ACTIONs.actionDoInvate);
        getActivity().registerReceiver(mNewsInviteBroadcastReceiver, myIntentFilter);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        registerBroadcastReceiver();
    }

    public void clearAll() {
        mInviteDatas.clear();
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        initData();
        initView();
        return view;
    }

    // 初始化数据
    private void initData() {
        handler = new Handler();
        // 通知Service初始化评论内容
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                noticeServiceInit();
            }
        }, 500);
    }

    private void initView() {
        view = View.inflate(getActivity(), R.layout.yn_news_list, null);
        rv_news_list = (RecyclerView) view.findViewById(R.id.rv_news_list);

        mRefreshlayout = (SwipeRefreshLayout) view.findViewById(R.id.news_invite_refresh);
        mRefreshlayout.setColorSchemeColors(getResources().getColor(R.color.yncolor));
        mRefreshlayout.setProgressViewOffset(false, 0, (int) TypedValue
                .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, getResources()
                        .getDisplayMetrics()));
        mRefreshlayout.setOnRefreshListener(this);
        // 初始加载刷新
        mRefreshlayout.setRefreshing(true);
        mLinearLayoutManager = new WrapContentLinearLayoutManager(getActivity());
        rv_news_list.setLayoutManager(mLinearLayoutManager);
        rv_news_list.setItemAnimator(new FadeInAnimator(new OvershootInterpolator(1f)));
        rv_news_list.getItemAnimator().setAddDuration(300);
        rv_news_list.getItemAnimator().setRemoveDuration(300);
        rv_news_list.getItemAnimator().setMoveDuration(300);
        rv_news_list.getItemAnimator().setChangeDuration(300);

        mAdapter = new NewsInviteAdapter(this, getActivity(), mInviteDatas);
        mYNRecyclerViewAdapter = new YNRecyclerViewAdapter(mAdapter);
        rv_news_list.setAdapter(mYNRecyclerViewAdapter);

        rv_news_list.addOnScrollListener(new EndlessRecyclerOnScrollListener() {
            @Override
            public void onLoadNextPage(View view) {
                super.onLoadNextPage(view);
                // 已经到底，返回
                if (isBottom) {
                    return;
                }
                // 加载中，返回
                LoadingFooter.State state = RecyclerViewStateUtils.getFooterViewState(rv_news_list);
                if (state == LoadingFooter.State.Loading) {
                    return;
                }
                // 加载下一页
                RecyclerViewStateUtils.setFooterViewState(getActivity(), rv_news_list, 10, LoadingFooter.State.Loading, null);
                rv_news_list.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        loadInvites();
                    }
                }, 500);
            }
        });
    }

    private void loadInvites() {
        if (mInviteDatas.size() <= 0) {
            return;
        }
        Intent mIntent = new Intent(getActivity(), NewsService.class);
        mIntent.setAction(ACTIONs.actionInviteNews);
        mIntent.putExtra(ACTIONs.aNeedId, mInviteDatas.getLast().getIgid());
        mIntent.putExtra(ACTIONs.aNeedType, CommonConstants.YNS_SIGN_LOAD);
        getActivity().startService(mIntent);
    }

    // 更新邀请消息
    private void updateView(List<YNNewsInvite> inviteList, String direction) {
        switch (direction) {
            case ACTIONs.aAddTop:
                for (int i = 0; i < inviteList.size(); i++) {
                    mInviteDatas.addFirst(inviteList.get(i));
                }
                break;
            case ACTIONs.aAddBottom:
                for (int i = 0; i < inviteList.size(); i++) {
                    mInviteDatas.addLast(inviteList.get(i));
                }
                if (inviteList.size() == 0) {
                    isBottom = true;
                    RecyclerViewStateUtils.setFooterViewState(getActivity(), rv_news_list, 10, LoadingFooter.State.TheEnd, null);
                } else {
                    RecyclerViewStateUtils.setFooterViewState(rv_news_list, LoadingFooter.State.Normal);
                }
                break;
        }
        mRefreshlayout.setRefreshing(false);
        mAdapter.notifyDataSetChanged();
    }

    // 分析并执行动作
    BroadcastReceiver mNewsInviteBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case ACTIONs.actionInviteUpdate:
                    List<YNNewsInvite> ll_news_invite = (List<YNNewsInvite>) intent.getSerializableExtra(ACTIONs.aAddData);
                    String direction = intent.getStringExtra(ACTIONs.aAddDirection);
                    updateView(ll_news_invite, direction);
                    break;
                case ACTIONs.actionDoInvate:
                    YNNewsInvite mInvate = (YNNewsInvite) intent.getSerializableExtra(ACTIONs.aInvateDatas);
                    mInviteDatas.addFirst(mInvate);
                    mAdapter.notifyDataSetChanged();
                    break;
            }
        }
    };

    // 接受邀请
    public void invateYes(final int type, final int position, String groupId, String msgId) {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(application.getCurID()));
        mParam.put(CommonConstants.YNS_GROUP_ID, groupId);
        mParam.put(CommonConstants.YNS_MESSAGE_ID, msgId);
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynAgreeInvate))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNAlbumResponse resInvateY = gson.fromJson(s, YNAlbumResponse.class);
                        if (ReqUtils.isSuccess(resInvateY.getCode())) {
                            Intent statintentbtnjoin = new Intent(ACTIONs.record);
                            statintentbtnjoin.putExtra("key", "邀请码_4");
                            statintentbtnjoin.putExtra("value", 1);
                            getActivity().sendBroadcast(statintentbtnjoin);
                            // 更新本地组
                            if (resInvateY.getData() != null && resInvateY.getData().get(0) != null) {
                                switch (type) {
                                    case 1:
                                        YNAlbum invateY = resInvateY.getData().get(0);
                                        Intent upIntent = new Intent(ACTIONs.actionInvateGroup);
                                        upIntent.putExtra(ACTIONs.aAlbumItem, invateY);
                                        upIntent.putExtra(ACTIONs.IsAdd, true);
                                        getActivity().sendBroadcast(upIntent);
                                        break;
                                    case 2:
                                        break;
                                }
                            } else {
                                Toast.makeText(getActivity(),resInvateY.getMsg(), Toast.LENGTH_SHORT).show();
                            }
                            Intent intent = new Intent(ACTIONs.AddMember);
                            getActivity().sendBroadcast(intent);
                            mInviteDatas.remove(position);
                            mAdapter.notifyDataSetChanged();
                        } else {
                            Toast.makeText(getActivity(), CommonConstants.TIP_UNKNOW, Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        Toast.makeText(getActivity(), CommonConstants.YN_NET_LINK, Toast.LENGTH_SHORT).show();
                    }
                });
        liteHttp.executeAsync(req);
    }

    // 删除News
    public void deleteNews(final int position, String msgId, final boolean isInvate) {
        String newsUrl = getString(R.string.BASE_URL) + getString(R.string.ynDeleteInvMessage);
        if (!isInvate) {
            newsUrl = getString(R.string.BASE_URL) + getString(R.string.ynDeleteComMessage);
        }
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_MESSAGE_ID, msgId);
        StringRequest req = new StringRequest(newsUrl)
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNCommonResponse resInvateN = gson.fromJson(s, YNCommonResponse.class);
                        if (ReqUtils.isSuccess(resInvateN.getCode())) {
                            mInviteDatas.remove(position);
                            mAdapter.notifyDataSetChanged();
                        } else {
                            Toast.makeText(getActivity(), CommonConstants.TIP_UNKNOW, Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        Toast.makeText(getActivity(), CommonConstants.TIP_UNKNOW, Toast.LENGTH_SHORT).show();

                    }
                });
        liteHttp.executeAsync(req);
    }

    // 通知后台初始化数据
    private void noticeServiceInit() {
        if (getActivity() == null) {
            return;
        }
        Intent mIntent = new Intent(getActivity(), NewsService.class);
        mIntent.setAction(ACTIONs.actionInviteNews);
        mIntent.putExtra(ACTIONs.aNeedId, 0);
        mIntent.putExtra(ACTIONs.aNeedType, CommonConstants.YNS_SIGN_INITS);
        getActivity().startService(mIntent);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        getActivity().unregisterReceiver(mNewsInviteBroadcastReceiver);
    }

    @Override
    public void onRefresh() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                mRefreshlayout.setRefreshing(false);
            }
        }, 3000);
    }

    // 友盟统计
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("MainScreen");
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("MainScreen");
    }
}